package com.code.springbootwebsocket.controller.v6;

import com.code.springbootwebsocket.model.InMessage;
import com.code.springbootwebsocket.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户群聊控制层
 *
 * @author: liyufei
 * @date: 2019-02-17 10:10
 */
@Controller
public class UserChatController {

    @Autowired
    private WebSocketService webSocketService;

    // 模拟数据库用户的数据
    public static Map<String, String> userMap = new HashMap<>();
    static {
        userMap.put("jack", "123");
        userMap.put("mary", "123");
        userMap.put("tom", "123");
        userMap.put("tim", "123");
    }

    // 在线用户存储
    public static Map<String, User> onlineUser = new HashMap<>();
    static {
        onlineUser.put("123", User.builder().username("admin").password("888").build());
    }

    /**
     * 功能描述：用户登录
     */
    @RequestMapping(value="login", method=RequestMethod.POST)
    public String userLogin( @RequestParam(value="username", required=true)String username,
                             @RequestParam(value="pwd",required=true) String pwd, HttpSession session) {

        String password = userMap.get(username);
        if (pwd.equals(password)) {
            User user = new User(username, pwd);
            String sessionId = session.getId();
            onlineUser.put(sessionId, user);
            return "redirect:/v6/chat.html";
        } else {
            return "redirect:/v6/error.html";
        }

    }

    @Scheduled(fixedRate = 2000)
    public void onlineUser() {

        webSocketService.sendOnlineUser(onlineUser);
    }

    @MessageMapping("/v6/chat")
    public void topicChat(InMessage message, SimpMessageHeaderAccessor headerAccessor){
        String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString();
        User user = onlineUser.get(sessionId);
        message.setFrom(user.getUsername());
        webSocketService.sendTopicChat(message);

    }


}
